/*************************************************************************
	> File Name: Composite.cc
	> Author: Joker
	> Mail: mahongtao@foxmail.com 
	> Created Time: 2020-09-22 01:03:30
 ************************************************************************/

#include "Composite.h"

#include <iostream>
#include <algorithm>

using std::cout;
using std::endl;

void Component::ADD(Component * pChild){
    cout << "Component::ADD(Component *)" << endl;
}

void Component::Remove(Component * pChild){
    cout << "Component::Remove(Component *)" << endl;
}

Component * Component::GetChild(size_t index){
    return nullptr;
}

void Leaf::Operation(){
    cout << "Operation by Leaf" << endl;
}

Composite::Composite(){
    cout << ">> Composite()" << endl;
}

Composite::~Composite(){
    cout << ">> ~Composite()" << endl;

    list<Component *>::iterator iter;
    for(iter = _listComponent.begin(); iter != _listComponent.end(); ++iter){
        list<Component *>::iterator tmp;
        tmp = iter;
        delete (*tmp);
    }
}

void Composite::ADD(Component * pChild){
    _listComponent.push_back(pChild);
}

void Composite::Remove(Component * pChild){
    list<Component *>::iterator iter;
    iter = find(_listComponent.begin(), _listComponent.end(), pChild);
    if(iter != _listComponent.end()){
        _listComponent.erase(iter);
    }
}

Component * Composite::GetChild(size_t index){
    if(index <= 0 || index > _listComponent.size()){
        return nullptr;
    }

    list<Component *>::iterator iter;
    iter = _listComponent.begin();
    for(size_t i = 1; i <= _listComponent.size(); ++i, ++iter){
        if(i == index){
            break;
        }
    }

    return *iter;
}

void Composite::Operation(){
    cout << "Operation of Composite" << endl;
    
    list<Component *>::iterator iter;
    for(iter = _listComponent.begin(); iter != _listComponent.end(); ++iter){
        (*iter)->Operation();
    }
}

